﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using IronPython.Hosting;

namespace Warensoft.PythonExtension
{
    /// <summary>
    /// 加载指定文件夹内的Python脚本
    /// </summary>
    public class DynamicIpyFolderLoader:IpyLoaderBase 
    {
        /// <summary>
        /// 构造方法
        /// </summary>
        public DynamicIpyFolderLoader()
        {

        }
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <remarks>使用该重载形式会导致指定目录下的Python脚本文件被自动加载！</remarks>
        /// <param name="plugInFolder">Python脚本所在的目录</param>
        public DynamicIpyFolderLoader(string plugInFolder)
        {
            this.PlugInFolder = plugInFolder;
            this.Load();
        }
        /// <summary>
        /// Python脚本所在的目录
        /// </summary>
        public string PlugInFolder
        {
            get;
            set;
        }
        private Dictionary <string,dynamic> callbackObjectList=new Dictionary<string,dynamic> ();
        /// <summary>
        /// 用于获取回调的Python对象的列表
        /// </summary>
        public Dictionary<string, dynamic> CallbackObjectList
        {
            get
            {
                return this.callbackObjectList;
            }
           
        }
        /// <summary>
        /// 加载指定目录下的Python脚本
        /// </summary>
        public override  void Load()
        {
            if (this.PlugInFolder==null ||this.PlugInFolder =="")
            {
                throw new Exception("请指定脚本文件所在的目录！");
            }
            var runtime = Python.CreateRuntime();
            var files = Directory.GetFiles(this.PlugInFolder ,"*.py");
            if (this.callbackObjectList ==null )
            {
                this.callbackObjectList =new Dictionary<string,dynamic> ();

            }
            this.callbackObjectList.Clear();
            foreach (var file in files)
            {
                dynamic script = runtime.UseFile(file);
                this.callbackObjectList.Add(Path.GetFileNameWithoutExtension(file),script);
            }
            this.OnScriptLoaded();
        }
    }

}
